package com.dg.controller;

import com.dg.common.PageQuery;
import com.dg.common.PageResult;
import com.dg.common.ServerResponse;
import com.dg.dto.UserDto;
import com.dg.param.LoginParam;

import com.dg.param.UserParam;
import com.dg.pojo.User;
import com.dg.service.UserService;
import com.dg.util.JwtUtil;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author mrq
 */
@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "login")
    public ServerResponse<Map<String,String>> login(LoginParam param){
        User user = userService.login(param);
        if(user == null){
            return ServerResponse.createByError("账号或密码错误");
        }
        String token = JwtUtil.createJwt(user.getId().toString() ,user);
        Map<String,String> map = Maps.newHashMap();
        map.put("name", user.getUsername());
        map.put("token", token);
        return ServerResponse.createBySuccess(map);
    }

    @RequestMapping("getUserInfo")
    public ServerResponse<User> getUserInfo(){
        Claims claims = (Claims)request.getAttribute("Claims");

        User user = User.builder().id(Integer.parseInt(claims.getId())).username(claims.getSubject()).phone(claims.get("phone").toString())
                .deptId(Integer.parseInt(claims.get("deptId").toString())).remark(claims.get("remark").toString()).build();
        return ServerResponse.createBySuccess(user);
    }

    @RequestMapping("list")
    public ServerResponse<PageResult<UserDto>> list(Integer deptId, PageQuery pageQuery){
        return ServerResponse.createBySuccess(userService.list(deptId, pageQuery));
    }

    @RequestMapping("save")
    public ServerResponse<List<User>> save(UserParam param){
        userService.save(param);
        return ServerResponse.createBySuccess();
    }

    @RequestMapping("update")
    public ServerResponse update(UserParam param){
        userService.update(param);
        return ServerResponse.createBySuccess();
    }

    @RequestMapping("delete")
    public ServerResponse delete(Integer id){
        userService.delete(id);
        return ServerResponse.createBySuccess();
    }

}
